package com.jhrc.portal.ws.status;

import com.jhrc.portal.ws.ClientInstance;
import com.jhrc.portal.ws.NettyWebsocketClient;
import com.jhrc.portal.ws.WebsocketClientInstance;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 【客户端连接状态巡检员】----全靠它来断线重连
 * @author luanxd
 * @date 2020-05-18
 */
public class StatusInspector implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(StatusInspector.class);

    /**
     * 被监控的WS 客户端实例
     */
    private ClientInstance clientInstance;

    /**
     * websocket client
     */
    private NettyWebsocketClient websocketPushClient;

    /**
     * 是否正在运行中
     */
    private boolean running = true;

    /**
     * 检查是否活着的间隔
     */
    private long DEFAULT_CHECK_ALIVE_DURATION = 3;

    public StatusInspector(NettyWebsocketClient client){
        websocketPushClient = client;
    }

    @Override
    public void run() {

        setCustomizedConfig();

        try{

            while (running){

                Channel channel = websocketPushClient.getChannel();
                if (channel == null || !channel.isActive()){

                    logger.info("channel is not live");

                    Boolean autoRebootClient = websocketPushClient.getWebsocketConfig().getAutoRebootClient();
                    if (autoRebootClient != null){
                        if (autoRebootClient.booleanValue()){

                           // clientInstance.closeConnection();
                            //clientInstance.connect();
                            clientInstance = new WebsocketClientInstance(websocketPushClient);
                            clientInstance.connect();
                        }

                        running = false;

                    }

                }else{
                    logger.info("status: " + channel.id()+" channel is working");
                }

                TimeUnit.SECONDS.sleep(DEFAULT_CHECK_ALIVE_DURATION);
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.warn("",e);
        }

    }

    /**
     * set customized configuration
     */
    protected void setCustomizedConfig(){
        if (clientInstance != null){
        	Long configCheckLiveDuration = clientInstance.getWebsocketClient().getWebsocketConfig().getCheckLiveDuration();
        	
          if ( configCheckLiveDuration != null){
        	  
        	  if (configCheckLiveDuration <= 0){
        		  throw new RuntimeException("invalid configuration of the parameter checkLiveDuration");
        	  }
        	  
              DEFAULT_CHECK_ALIVE_DURATION = configCheckLiveDuration;
          }
        }
    }


    /**
     * shut down inspector gracefully after thread became wakeup and next running
     */
    public void shutdownInspectorGracefully(){
        running = false;
    }


}
